package com.cl.mypureframe.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;


import com.cl.mypureframe.R;
import com.cl.mypureframe.conn.Conn;
import com.cl.mypureframe.util.FileProvider7;
import com.cl.mypureframe.util.FileUtil;
import com.cl.mypureframe.util.GLobalConstant;
import com.cl.mypureframe.util.Log;
import com.cl.mypureframe.util.UtilFile;
import com.cl.mypureframe.util.UtilToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Class: BasePicActivity
 * @Description: 选择图片，拍照的Activity基类
 * @Author: ChenLei
 * @Date: 2020/11/21---15:28
 */
public class BasePicActivity extends BaseActivity {
    private static final int RC_TAKE_PHOTO = 1;
    private static final int RC_CHOOSE_PHOTO = 2;
    private PopupWindow popWindow;
    private String mTempPhotoPath;
    private Map<Integer, String> picUrlMap;// 服务器返回的图片地址结合
    private File photoFile;
    protected int tabIndex;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        picUrlMap = new HashMap<>();
        // 动态权限申请
        applyPermissions(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA);
        initPopupWindow();
    }

    protected Map<Integer, String> getPicUrlMap() {
        return picUrlMap;
    }

    protected List<String> getPicUrlList() {
        List<String> picList = null;
        if (!picUrlMap.isEmpty()) {// 是否有图片
            picList = new ArrayList<>(getPicUrlMap().values());
        }
        return picList;
    }

    protected void showPop(int index) {
        tabIndex = index;
        showPwFromBottom(popWindow);
    }

    protected void showPop() {
        showPwFromBottom(popWindow);
    }

    private void initPopupWindow() {
        popWindow = initPopWindowFromBottom(R.layout.pw_selectpic);
        View pView = popWindow.getContentView();

        TextView tvCancel = pView.findViewById(R.id.tv_cancel);
        TextView tvTakePhoto = pView.findViewById(R.id.tv_takephoto);
        TextView tvPic = pView.findViewById(R.id.tv_pickpic);
        // 拍照
        tvTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
                takeAPicture();
            }
        });

        // 从相册选取
        tvPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
                pickPhoto();
            }
        });
        // 取消
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
    }

    // 从相册选取
    protected void pickPhoto() {
        Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentToPickPic, RC_CHOOSE_PHOTO);
    }

    // 拍照
    protected void takeAPicture() {
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (UtilFile.createPathFile(GLobalConstant.PHOTO_PATH)) {
            photoFile = new File(GLobalConstant.PHOTO_PATH, "photo_" + System.currentTimeMillis() + ".jpeg");
            mTempPhotoPath = photoFile.getAbsolutePath();
            Uri imageUri = FileProvider7.getUriForFile(this, photoFile);
            intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intentToTakePhoto, RC_TAKE_PHOTO);
        }
    }

    // 上传图片接口
//    private void uploadPicExecute(File file) {
//        Log.e(TAG, "file.exists()", file.exists());
//        MultipartBody.Builder builder = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)//表单类型
//                .addFormDataPart("userId", getUserId());
//        MediaType mediaType = MediaType.Companion.parse("multipart/form-data");
//        RequestBody imageBody = RequestBody.Companion.create(file, mediaType);
//        builder.addFormDataPart("file", file.getName(), imageBody);// imgfile 后台接收图片流的参数名
//        List<MultipartBody.Part> parts = builder.build().parts();
//
//        RetrofitUtil<ResVerifyMod> retrofitUtil = new RetrofitUtil<>();
//        Call<ResVerifyMod> call = retrofitUtil.getRetrofit().postUploadFile(parts);
//        retrofitUtil.connAction(call, this, new OnResponseCallback<ResVerifyMod>() {
//            @Override
//            public void onStartCallback() {
//            }
//
//            @Override
//            public void onSuccessCallback(Response<ResVerifyMod> response) {
//                ResVerifyMod resVerifyMod = response.body();
//                if (resVerifyMod.getCode() == Conn.CODE_SUCCESS) {
//                    picUrlMap.put(tabIndex, resVerifyMod.getContent());
//                } else {
//                    UtilToast.show(resVerifyMod.getMessage());
//                }
//            }
//
//            @Override
//            public void onErrorCallback() {
//            }
//
//            @Override
//            public void onEndCallback() {
//            }
//        });
//
//    }

    protected void getFilePath(String filePath) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case RC_CHOOSE_PHOTO:// 选择相册返回结果
                if (data != null) {
                    Uri uri = data.getData();
                    String filePath = FileUtil.getFilePathByUri(this, uri);
                    if (!TextUtils.isEmpty(filePath)) {
                        getFilePath(filePath);
                    }
                }

                break;
            case RC_TAKE_PHOTO:// 拍照返回结果
                if (photoFile.exists()) {
                    getFilePath(mTempPhotoPath);
                }
                break;
        }
    }

}
